import React, { Component } from 'react';
import { NavigationEvents } from 'react-navigation';
import {
  StyleSheet, Text, View, TouchableOpacity,
  Image, PixelRatio, FlatList, Alert
} from "react-native";
import { API, API_GENERATE } from '../../../../config/api';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import HTTP from '../../../../utils/http';
import ToastUtil from '../../../../utils/toast';
import { RefuseModal } from '../../../../component/ModalVerifylComponent.js';
import { Common } from '../../../../component/common/Common';
import { NewAccountHome } from '../../../../components/common/newAccountHome';
import { MDMCodeCpt } from '../../highSeas/_components/MDMCodeCpt';

const scale = GLOBAL.SCALE;
const arrowIcon = require('../../../../imgs/sanjiao3.png')

const LIST = [
  {
    label: '产品认领',
    params: {
      applyType: 'APPLYP',
    }
  },
  {
    label: '产品分配',
    params: {
      applyType: 'TRANS',
    }
  }
]

export class GoodsListPage extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    return {
      headerTitle: '产品审批',
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../../imgs/goBackEmpty.png')} />),
      headerStyle: style.head.headerStyle,
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center',
      }
    }
  };

  constructor(props) {
    super(props);
    this.state = {
      tabIndex: 0,
      companyIndex: 0,
      tabItem: this.props.navigation.state.params.tabItem ? this.props.navigation.state.params.tabItem : 0,
      status: 'data',
      refreshIcon: false,
      listData: [],
      resAuditcntList: [],
      itemData: {},
      params: {
        applyType: this.props.navigation.state.params.applyType ? this.props.navigation.state.params.applyType : 'APPLYP'
      },
      isTablet: true,
      cntList: true,
      isDataItem: true,
      itemAuditingletedCnt: '0',
      itemAuditRejectCntCnt: '0',
      totalPage: '0',
      alertShow: false,
      options: [],
      choice: {}
    }
    this.reload = true; // 判断是整个页面刷新还是下拉刷新
    this.totalPage = 1;
    this.pageParams = {
      pageNo: 1,
      pageSize: 10,
    }
  }

  async componentWillMount () {
    await this.getSorage();
    await this.initPage();
    await this.init();
  }

  //获取业务组织
  async getSorage () {
    let resCount = await HTTP.POST(API_GENERATE(API.PRODUCT_APPLY_AUDITLIST_MUL))
    let options = resCount || [];
    options.map(item => {
      item.rowCount = item.paginationModel.recordCount
    })
    this.setState({
      options,

    })
  }

  //初始化数据
  init = async () => {
    const { options, companyIndex } = this.state;
    const { corpId } = options[companyIndex] || {};
    let resTableList = await HTTP.POST(API_GENERATE(API.APPLY_AUDIT_CNT), { corpId })
    if (resTableList) {
      let resAuditcntList = resTableList.cntList
      this.setState({
        resAuditcntList,
      })
    } else {
      this.setState({
        status: 'error'
      })
    }
  }

  initPage = async (refreshIcon) => {
    this.setState({
      status: this.reload ? 'loading' : 'data',
      refreshIcon: !this.reload && this.pageParams.pageNo == '1'
    })
    let { corpId } = this.state.options[this.state.companyIndex] || {};
    this.params = {
      pageNo: this.pageParams.pageNo,
      pageSize: this.pageParams.pageSize,
      applyType: this.state.params.applyType,
      corpId: corpId || '',
    }
    let res = await HTTP.POST(API_GENERATE(API.PRODUCT_APPLY_AUDITLIST), this.params)
    if (res) {
      let responseData = res.rows;
      this.setState({
        status: responseData && responseData.length > 0 ? 'data' : 'empty',
        listData: this.pageParams.pageNo == '1' ? responseData : this.state.listData.concat(responseData),
        refreshIcon: false,
        totalPage: res.totalPage,
        choice: this.state.options[this.state.companyIndex] || {}
      })
      this.pageParams.pageNo = res.pageNo++;
    } else {
      this.setState({
        status: 'error'
      })
    }
  }

  loadMore = () => {
    if (this.state.totalPage > this.pageParams.pageNo) {
      this.pageParams.pageNo++;
      this.reload = false;
      this.initPage();
    }
  }

  refresh = () => {
    this.pageParams.pageNo = 1;
    if (this.state.totalPage >= this.pageParams.pageNo) {
      this.reload = false;
      this.initPage();
    }
  }

  _tabList = (items, tabItem) => {
    this.reload = true;
    this.pageParams.pageNo = 1;
    this.setState({
      tabItem,
      params: {
        applyType: items.params.applyType,
      },
      totalPage: '0',
    }, () => {
      this.pageParams.pageNo = 1;
      this.initPage();
    })

  }

  onErrorRefresh = () => {
    let { tabIndex } = this.state;
    if (tabIndex != 2) {
      this.initPage();
    }
  }

  goSkipPage = (item) => {
    let { tabItem } = this.state;
    this.props.navigation.navigate('ProductClaimPage', {
      applyId: item.applyId ? item.applyId : '',
      auditResult: item.auditResult,
      remark: item.remark,
      title: tabItem ? '分配' : '认领',
      isJudge: true,
      applyType: item.applyType,
      tabItem,
      choice: this.state.choice,
      mdmCode: item.mdmCode
    })
  }

  // 同意
  consentCreate = (type, item) => {
    item.auditResult = type;
    item.remark = '';
    if (item) {
      this.setState({
        showRejectModal: true,
        itemData: item,
      })
    } else {
      ToastUtil.showWarning('没有数据')
    }
  }

  // 审批
  approve = async (remark) => {
    const { options, companyIndex } = this.state;
    const { corpId } = options[companyIndex] || {};
    const data = this.state.itemData;
    let requestParams = {
      businessKey: data.applyId,
      auditResult: data.auditResult,
      remark,
      corpId
    };
    let text = requestParams.auditResult != 1 ? '驳回' : '审批';
    this.setState({
      showRejectModal: false,
      status: 'loading'
    })
    let res = await HTTP.POST(API_GENERATE(API.PRODUCT_DEAL_APPLY_AUDIT), requestParams);
    if (res) {
      ToastUtil.showSuccess(`${text}成功`).then(() => {
        this.reloadPage()
      })
    } else {
      this.setState({
        status: 'data'
      })
    }
  }

  reloadPage = () => {
    this.pageParams.pageNo = 1;
    this.reload = true;
    this.init();
    this.initPage();
  }

  _approvalListItim = (data) => {
    let { tabItem, } = this.state
    let item = data.item;
    return (
      <View style={{
        marginTop: 20 * scale, paddingLeft: 12 * scale,
        paddingRight: 12 * scale,
      }}>
        <View style={{ marginBottom: 7 * scale, flexDirection: 'row', justifyContent: 'flex-end' }}>
          <Text style={styles.itemLightText}>{item && item.createTime ? item.createTime : '--'}</Text>
        </View>
        <TouchableOpacity activeOpacity={.6} style={styles.itemWrap}
          onPress={() => {
            this.goSkipPage(item)
          }}
        >
          <View style={{ flexDirection: 'row', marginBottom: 15 * scale, marginTop: 10 * scale, paddingLeft: 12 * scale, paddingRight: 12 * scale, }}>
            <View style={{ flex: 4, flexDirection: 'row', alignItems: 'center' }}>
              <Text style={styles.itemLightText}>{item && item.companyName ? item.companyName : '--'}</Text>
              {!item.mdmCode ? <View style={{ marginLeft: 5 * scale }}><MDMCodeCpt /></View> : null}
            </View>
            <View style={{ flex: 1 }}>
              <Text style={styles.itemLightColor}>{tabItem == 0 ? '产品认领' : tabItem == 1 ? '产品分配' : ''}</Text>
            </View>
          </View>
          <Text style={{ fontSize: 10 * scale, paddingLeft: 12 * scale, paddingBottom: 12 * scale, color: '#848A96' }}>(业务组织：{this.state.choice.corpName || '-'})</Text>
          <View style={styles.itemBorder}></View>
          <View style={{ marginBottom: 15 * scale, marginTop: 10 * scale, }}>

            {tabItem != 0 ? (
              <View>
                <View style={styles.itemProductConter}>
                  <View style={styles.itemGoodsNumber}>
                    <Text style={styles.itemNumber}>本次分配产品数</Text>
                  </View>
                  <Text style={styles.itemNumber}>{item && item.goodsCnt ? item.goodsCnt : '--'}</Text>
                </View>
                <View style={styles.itemProductConter}>
                  <View style={styles.itemType}>
                    <Text style={styles.itemNumber}>接收人</Text>
                  </View>
                  <Text style={styles.itemConter}>{item && item.bizStaffName ? item.bizStaffName : '--'}</Text>
                  <Text style={[styles.itemConter, { marginLeft: 10 * scale }]}>{item && item.bizStaffOranName ? item.bizStaffOranName ? `(${item.bizStaffOranName})` : '' : ''}</Text>
                </View>
              </View>
            ) : (
                <View style={styles.itemProductConter}>
                  <View style={styles.itemGoodsNumber}>
                    <Text style={styles.itemNumber}>本次认领产品数</Text>
                  </View>
                  <Text style={styles.itemNumber}>{item && item.goodsCnt ? item.goodsCnt : '--'}</Text>
                </View>
              )

            }

            <View style={styles.itemProductConters}>
              <View style={[styles.itemType, styles.itemTypeName]}>
                <Text style={styles.itemNumber}>操作人</Text>
              </View>
              <Text style={styles.itemConters}>
                {item && item.createByName || item.bizTeamName ? `${item.createByName || '--'} | ${item.bizTeamName || '--'}` : '--'}
              </Text>
              <Image source={arrowIcon} style={styles.arrowIcon} />
            </View>
            <View style={styles.itemBorder}></View>
            <View style={styles.itemDayTime}>
              <Text style={[styles.consent]} onPress={() => { this.consentCreate(1, item) }}>同意</Text>
              <Text style={styles.itemdown} onPress={() => { this.consentCreate(0, item) }}>驳回</Text>
            </View>
          </View>
        </TouchableOpacity>
      </View>
    )
  }

  render () {
    let { tabIndex, listData, tabItem, refreshIcon, status, resAuditcntList, showRejectModal, alertShow,
      choice, options, itemData } = this.state;
    return (
      <View style={styles.container}>
        <NavigationEvents onWillFocus={async () => {
          await this.getSorage();
          await this.init();
          await this.initPage();
        }} />
        {options.length > 1 ?
          <NewAccountHome
            fn={(val) => {
              this.setState({ companyIndex: val }, () => {
                this.pageParams.pageNo = 1;
                this.reloadPage()
              })
            }}
            options={options}
            choice={choice} />
          : null}
        <View style={[styles.stateView, styles.marginStyle]}>
          {LIST.map((items, index) => {
            return (
              <TouchableOpacity key={index} style={[styles.stateItem, tabItem == index ? styles.stateItemActive : null]} onPress={() => { this._tabList(items, index) }}>
                <Text style={[styles.stateItemText, tabItem == index ? styles.stateItemTextActive : null]}>{items.label}</Text>
                <View style={[resAuditcntList[index] && resAuditcntList[index].incompletedCnt > 0 ? styles.stateItemInfo : null, tabItem == index ? styles.stateItemInfoActive : null]}></View>
              </TouchableOpacity>
            )
          })
          }
        </View>
        {
          status == 'data' ? (
            <View style={styles.body}>
              <FlatList
                data={listData}
                renderItem={
                  this._approvalListItim
                }
                refreshing={refreshIcon}
                onRefresh={() => { this.refresh() }}
                onEndReachedThreshold={1}
                onEndReached={() => { this.loadMore() }}
              />
            </View>

          ) : (<View style={{ flex: 1 }}>
            <PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this.onErrorRefresh} />
          </View>)
        }
        <RefuseModal
          titleText={'审批意见'}
          placeholderText={itemData.auditResult ? '请输入同意原因' : null}
          propsDefaultValue={itemData.auditResult ? '审批同意' : '审批驳回'}
          visible={showRejectModal}
          btnPress={(text) => {
            this.approve(text);
          }}
          bgPress={() => {
            this.setState({
              showRejectModal: false,
            });
          }} />
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: style.color.bgGray
  },
  headBox: {
    backgroundColor: style.color.themeColor,
    height: 50 * scale,
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'space-around'
  },
  tabItems: {
    color: style.color.white,
    fontSize: 12 * scale,
    width: '35%',
    textAlign: 'center',
    marginTop: 20 * scale,
    opacity: .8
  },
  marginStyle: {
    marginLeft: 15 * scale,
    marginRight: 15 * scale
  },
  tabItemActive: {
    opacity: 1
  },
  stateView: {
    flexDirection: 'row',
    marginTop: 15 * scale,
    marginBottom: 15 * scale
  },
  stateItem: {
    padding: 8 * scale,
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    borderRadius: 20 * scale,
    marginRight: 10 * scale,
    flexDirection: 'row'
  },
  stateItemText: {
    paddingLeft: 2 * scale,
    paddingRight: 2 * scale,
    fontSize: 11 * scale,
    color: style.color.themeColor
  },
  stateItemInfo: {
    width: 5 * scale,
    height: 5 * scale,
    backgroundColor: style.color.fontRed1,
    borderRadius: 3 * scale,
    position: 'relative',
    top: -5 * scale
  },
  stateItemActive: {
    backgroundColor: style.color.themeColor,
  },
  stateActive: {
    backgroundColor: style.color.white,
  },
  stateItemTextActive: {
    fontSize: 11 * scale,
    color: style.color.white
  },
  stateItemInfoActive: {
    backgroundColor: style.color.white
  },
  body: {
    flex: 1,
    backgroundColor: style.color.bgGray
  },
  itemLightText: {
    fontSize: 12 * scale,
    color: '#272727',
    fontWeight: '500',
  },
  itemAccount: {
    fontSize: 12 * scale,
    color: '#272727',
  },
  itemDayTime: {
    justifyContent: 'flex-end',
    flex: 1,
    flexDirection: 'row'
  },
  consent: {
    paddingRight: 20 * scale,
    paddingLeft: 20 * scale,
    paddingTop: 8 * scale,
    paddingBottom: 8 * scale,
    fontSize: 12 * scale,
    opacity: 1,
    color: '#ffffff',
    alignItems: 'center',
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    borderRadius: 15 * scale,
    flexDirection: 'row',
    backgroundColor: style.color.themeColor,
    overflow: 'hidden'
  },
  itemdown: {
    fontSize: 12 * scale,
    color: style.color.themeColor,
    alignItems: 'center',
    paddingRight: 20 * scale,
    paddingLeft: 20 * scale,
    paddingTop: 8 * scale,
    paddingBottom: 8 * scale,
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    borderRadius: 15 * scale,
    marginRight: 20 * scale,
    flexDirection: 'row',
    marginLeft: 10 * scale,
  },
  itemTime: {
    fontSize: 12 * scale,
    color: '#272727',
    opacity: .8,
    paddingTop: 10 * scale,
    paddingRight: 10 * scale,
  },
  itemWrap: {
    backgroundColor: '#fff',
    width: '100%',
    borderRadius: 8 * scale,
    paddingTop: 14 * scale,
  },
  itemType: {
    width: 58 * scale,
    flexDirection: 'row',
    alignItems: 'flex-start',
    borderRadius: 4 * scale,
    marginRight: 10 * scale,
  },
  itemGoodsNumber: {
    width: 88 * scale,
    flexDirection: 'row',
    alignItems: 'flex-start',
    borderRadius: 4 * scale,
    marginRight: 10 * scale,
  },
  itemLightColor: {
    fontSize: 12 * scale,
    color: '#F60202',
    fontWeight: '500',
  },
  itemBorder: {
    height: 1 * scale,
    backgroundColor: '#E3E7F0',
    marginBottom: 15 * scale,
  },
  arrowIcon: {
    width: 8 * scale,
    height: 12 * scale,
    position: 'absolute',
    right: 0,
    top: 2 * scale,
    right: 32 * scale,
  },
  itemApplyAmount: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    paddingRight: 10 * scale,
  },
  itemNumber: {
    color: '#000000',
    fontSize: 12 * scale,
    fontWeight: '300',
  },
  itemConter: {
    color: '#000000',
    fontSize: 12 * scale,
    fontWeight: '600'
  },
  itemConters: {
    color: '#000000',
    fontSize: 12 * scale,
    fontWeight: '600',
    flexDirection: 'row',
    width: 210 * scale,
  },
  itemProductConter: {
    flexDirection: 'row',
    alignItems: 'center',
    position: 'relative',
    marginBottom: 15 * scale,
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
  },
  itemProductConters: {
    flexDirection: 'row',
    position: 'relative',
    marginBottom: 15 * scale,
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
  },
  accountSelect: {
    backgroundColor: style.color.themeColor,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center'
  },
  itemTypeName: {
    paddingTop: 2 * scale
  },
})